package cn.wonderland.resthome.controller;

import cn.wonderland.basic.util.BussinessException;
import cn.wonderland.resthome.service.INurseService;
import cn.wonderland.resthome.domain.Nurse;
import cn.wonderland.resthome.query.NurseQuery;
import cn.wonderland.basic.util.AjaxResult;
import cn.wonderland.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/nurse")
public class NurseController {
    @Autowired
    public INurseService nurseService;


    /**
     * 保存和修改公用的
     *
     * @param nurse 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Nurse nurse) {
        if (nurse.getId() != null) {
            Nurse byId = nurseService.findById(nurse.getId());
            if (byId.getOldmanCount() != 0) {
                throw new BussinessException("当前护工正在护理老人，不能修改信息！");
            }
            // 查找现在有多少个正常状态的护工 ---- 最多存在 **正常**状态下的10个护工
            List<Nurse> count = nurseService.getNurseCount();
            Integer state = nurse.getState();
            if (count.size() >= 10 && state == 26 && nurse.getNurseName().equals(byId.getNurseName())) {
                throw new BussinessException("很抱歉！最多存在10个正常状态员工！");
            }
            nurseService.update(nurse);
        } else {
            nurseService.add(nurse);
        }
        return AjaxResult.me().success();

    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        Nurse byId = nurseService.findById(id);
        if (byId.getOldmanCount() != 0) {
            throw new BussinessException("当前护工正在护理老人，不能删除信息！");
        }
        nurseService.delete(id);
        return AjaxResult.me().success();
    }

    //获取用户
    @GetMapping("/{id}")
    public Nurse get(@PathVariable("id") Long id) {
        return nurseService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<Nurse> list() {
        return nurseService.findAll();
    }

    /**
     * 查看所有正常状态的员工信息
     * 前端下拉列表只展示正常状态的员工
     *
     * @return
     */
    @GetMapping("/normalNurse")
    public List<Nurse> findNormalNurse() {
        return nurseService.getNurseCount();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<Nurse> json(@RequestBody NurseQuery query) {
        return nurseService.queryByPage(query);
    }

    /*
     * 批量删除信息
     * */
    @PatchMapping()
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        nurseService.batchDelete(ids);
        return AjaxResult.me().success();
    }
}
